from ui import ImageProcessorUI
from .base import ImageProcessor
import numpy as np
import cv2
from PIL import Image

class SmoothingProcessor(ImageProcessor):
    def process(self, image: Image.Image, **kwargs) -> Image.Image:
        """
        对图像进行平滑滤波处理。
        参数:
        - image: 输入图像 (PIL Image)
        - method: 滤波方法 ("average", "gaussian", "median")
        - kernel_size: 核大小 (奇数，如 3, 5, 7)
        返回:
        - Image.Image: 平滑后的图像
        """
        method = kwargs.get("method", "average")
        kernel_size = int(kwargs.get("kernel_size", 3))
        # 确保核大小是正奇数
        if kernel_size % 2 == 0:
            raise ValueError("核大小必须为奇数")
        # 转换为 NumPy 数组用于 OpenCV 处理
        img_array = np.array(image)
        if method == "average":
            processed = cv2.blur(img_array, (kernel_size, kernel_size))
        elif method == "median":
            processed = cv2.medianBlur(img_array, kernel_size)
        elif method == "gaussian":
            processed = cv2.GaussianBlur(img_array, (kernel_size, kernel_size), 0)
        else:
            raise ValueError(f"未知滤波方法: {method}")
        return Image.fromarray(processed)

    def get_ui_parameters(self, ui: "ImageProcessorUI") -> dict:
        """
        从 UI 获取参数
        """
        try:
            method = ui.smoothing_method_var.get()
            kernel_size = float(ui.kernel_scale.get())
            return {
                "method": method,
                "kernel_size": kernel_size
            }
        except Exception as e:
            ui.show_error(f"获取参数失败: {e}")
            return {}